package com.hsource.common.utils;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
//import com.plgolf.ushare.authentication.entity.UserRoleExt;

import io.jsonwebtoken.*;

public class JwtUtil {

    public static final String JWT_ID = UUID.randomUUID().toString();

    /**
     * 默
     */
    public static final String JWT_SECRET = "79e7c69681b8270162386e6daa53d1dc";
    public static final int JWT_TTL = 60*60*1000;  //millisecond


    /**
     * base64加密
     * @param key
     * @return
     */
    public static String convertToBase64(String key)
    {
        return "";
    }

    /**
     * 解密
     * @param jsonWebToken
     * @return
     */
    public static Claims parseJWT(String jsonWebToken) throws IOException
    {
        return parseJWT(jsonWebToken,JWT_SECRET);
    }

    /**
     * 解密
     * @param jsonWebToken
     * @param base64Security
     * @return
     */
    public static Claims parseJWT(String jsonWebToken, String base64Security) throws IOException{
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(base64Security.getBytes())
                    .parseClaimsJws(jsonWebToken).getBody();
            return claims;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new IOException("parseJWT error");
        }
    }

    /**
     * 前三个参数为自己用户token的一些信息比如id，权限，名称等。不要将隐私信息放入（大家都可以获取到）
     * @param map
     * @param base64Security
     * @return
     */
    public static String createJWT(Map<String, Object> map, String base64Security) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .setPayload(JSON.toJSONString(map))
                .signWith(signatureAlgorithm,base64Security.getBytes()); //估计是第三段密钥
        //生成JWT

        return builder.compact();
    }

    /**
     * 加密
     * @param map
     * @return
     */
    public static String createJWT(Map<String, Object> map) {
        return createJWT(map,JWT_SECRET);
    }

    /**
     * 加密
     * @param map
     * @return
     */
    public static <T> String createJWT(T obj) {
        String json = JSON.toJSONString(obj);
        return createJWT(json);
    }

    /**
     * 加密
     * @param map
     * @return
     */
    public static <T> String createJWT(T obj,String base64Security) {
        String json = JSON.toJSONString(obj);
        return createJWT(json,base64Security);
    }

    /**
     * 加密
     * @param json
     * @param base64Security
     * @return
     */
    public static String createJWT(String json,String base64Security) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .setPayload(json).signWith(signatureAlgorithm, base64Security.getBytes());
        return builder.compact();
    }

    /**
	     * 加密
	     * @param json
	     * @return
	     */
	    public static String createJWT(String json) {
	    	return createJWT(json,JWT_SECRET);
	    }


	public static boolean isTokenValid(String jwt) {
		try {
			parseJWT(jwt);
		} catch (Throwable e) {
			return false;
		}
		return true;
	}
	    public static void main(String[] args) throws Exception {
	       /* Map<String, Object> map = new HashMap<String, Object>();
	        map.put("province", "898765");
	        map.put("city", "898765");
	        map.put("appkey", "HMu1H/cmyKDOiHv41Y9lLROuOlOo+PPG8F4/RotRmNc=");
	        map.put("timestamp",System.currentTimeMillis());

	        //密钥
	        String keyt = "79e7c69681b8270162386e6daa53d1dc";
	        String token=JwtUtil.createJWT(map, keyt);
	        System.out.println("JWT加密的结果："+ token);
	        //System.out.println("JWT解密的结果："+ parseJWT(token, keyt));

	        //默认固定秘钥
	        String json=JSON.toJSONString(map);
	        token=JwtUtil.createJWT(json);
	        System.out.println("JWT加密的结果1："+ token);
	        System.out.println("JWT解密的结果1："+ parseJWT(token, keyt));
	        System.out.println("JWT解密的结果getExpiration："+ parseJWT(token).getExpiration());

	        //动态秘钥
	*//*        String secretKey=StringUtil.getCurrentTimeString();
	        token=JwtUtil.createJWT(json,secretKey);
	        System.out.println("JWT加密的结果2："+ token);
	        System.out.println("JWT解密的结果2："+ parseJWT(token, secretKey));*/

            String json="{\"uid\":\"abcde\",\"tms\":\"123456789\"}";

            String jwtJson = createJWT(json);

	        String json1 = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIxNjYyMjgwNjAyMCIsInRtcyI6IjE2MDMxNjY0NTcifQ.6PssiDIjxtXuYmVty7d210GF6ysnJQgG5J1tKUkX7jQ";
            System.out.println("JWT加密的结果2："+ jwtJson);

	        Claims cls=parseJWT(json1);
	        System.out.println("JWT解密的结果2："+ cls);

	      /*  ObjectMapper trans=new ObjectMapper();
	        String json2 = trans.writeValueAsString(cls);*/

//	        UserRoleExt urExt = JSON.parseObject(json2, UserRoleExt.class);

	        /*System.out.println("JWT解密的结果token："+ json2);
//	        System.out.println("JWT解密的结果urExt："+ urExt);*/



	    }
}

